package org.vectrics.mail.struts;

import java.io.File;

import org.apache.ecs.html.Input;
import org.vectrics.SystemException;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.util.StringUtils;
import org.vectrics.common.view.HtmlForm;
import org.vectrics.common.view.HtmlFormCheckBoxRow;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.Request;
import org.vectrics.struts.VectricsTagSupport;
import org.vectrics.user.Person;

/**
 * @author Mike Moore
 *
 */
public class BulkEmailStageFormTag extends VectricsTagSupport {
	public static final long serialVersionUID = 2357098787632489L;
	
	public static String FORM_ID = "stage_form";
	public static String ACTION_FORM_NAME = FORM_ID;
	public static String LETTER_REVIEW_FORM_ACTION = "";
	
	/**
	 * 
	 */
	public BulkEmailStageFormTag() {
		super();
	}

	
	/* (non-Javadoc)
	 * @see org.vectrics.struts.VectricsTagSupport#makeStartTag()
	 */
	@Override
	protected String makeStartTag() {
		StringBuffer html = new StringBuffer();
		html.append("<h1>Stage Form</h1>");
		String stagingDirectory = (String)this.getRequest().getAttribute("stagingDirectory");
		Person sender = (Person)this.getRequest().getAttribute("sender");
		File directory = new File(stagingDirectory);
		if (directory.exists() == false)
			throw new SystemException("StagingDirectory does not exist: " + stagingDirectory);
		
		HtmlForm htmlForm = new HtmlForm(this.getRequest(), ACTION_FORM_NAME, this.getPhrase("phrase.recipients"));
		htmlForm.setId(FORM_ID);
		htmlForm.setAction("/hrs-intranet/admin/mailer/send.do");
		boolean checked = true;
	
		String dateMillisParam = (String)this.getRequest().getAttribute("stageDateMillis");
		if (StringUtils.isNullOrBlank(dateMillisParam)) {
			throw new SystemException("Request attribute stageDateMillis not specified");
		}
		
		htmlForm.addHidden("stageDateMillis", dateMillisParam);
		String subject = (String)this.getRequest().getAttribute("subject");
		htmlForm.addReadOnlyText("subject", "Subject", subject);
		htmlForm.addHidden("subject", subject);

		String templateId = (String)this.getRequest().getAttribute("templateId");
		htmlForm.addHidden("templateId", templateId);

		String categoryId = (String)this.getRequest().getAttribute("categoryId");
		htmlForm.addHidden("categoryId", categoryId);
	
		
		String[] fileNames = directory.list();
		for (int i = 0; i < fileNames.length; i++) {
			String fileName = fileNames[i];
			if (fileName.startsWith("recip_")) {
				log.info("Recipient email file found in staging directory: " + fileName);
				String paramValue = fileName;
				String personIdStr = fileName.substring("recip_".length());
				Person recipient = CoreServiceLocator.getPersonService().findPersonById(new Long(personIdStr));
				String onCaptionClick = "javascript:showRecipientLetter(" + personIdStr 
					+ ", '" + this.getContextPath() + "', '" + this.getAuthPerson().getUser().getUserName()
					+ "', " + ThreadProperties.getDomain().getId() + ", '" + this.getAuthPerson().getUser().getPassword()
					+ "');";
				HtmlFormCheckBoxRow formRow = htmlForm.addCheckbox(recipient.getFullName(), paramValue, checked, onCaptionClick);
		    	formRow.getLabelDiv().setStyle("cursor: pointer");
			} 
		}
		
		htmlForm.addSubmitAndCancelButton();

		html.append(getJavascriptMethods(sender, stagingDirectory, dateMillisParam));
		
		Table mainTable = new Table();
		mainTable.setCellPadding(2);
		Row row = mainTable.addRow();
		Cell recipientsCell = row.addCell();
		recipientsCell.addElement(htmlForm.toString());
		
		row = mainTable.addRow();
		Cell letterCell = row.addCell();
		letterCell.addElement(makeLetterForm(this.getRequest()).toString());
		html.append(mainTable.toString());
		
		return (html.toString());
	};
	
	
	private HtmlForm makeLetterForm(Request request) {
		HtmlForm htmlForm = new HtmlForm(request, LETTER_REVIEW_FORM_ACTION, this.getPhrase("phrase.letter"));
		htmlForm.setId(LETTER_REVIEW_FORM_ACTION);
		htmlForm.setAction("/hrs-intranet/admin/mailer/send.do");
		htmlForm.addHidden("recipientId", "null");
		htmlForm.addReadOnlyText("letter_recipient", "Recipient", "");
		htmlForm.addEditForParam("Subject", "recipSubject", false);
		htmlForm.addTextAreaRowForParam("Body", "letterBody", 20, 60, false);
		return(htmlForm);
	}
	
	/**
	 * 
	 * @param stagingDirectory
	 * @param stagingDateMillis
	 * @return
	 */
	private String getJavascriptMethods(Person sender, String stagingDirectory, String stagingDateMillis) {
		StringBuffer methods = new StringBuffer();
		
		
		methods.append("<script type=\"text/javascript\">\r\n");
		
		methods.append(
				" function showRecipientLetter(recipientId, contextRoot, user, domainId, pcode, time) { \r\n" +
				"   log('showRecipientLetter() called');\r\n" +
				"	saveRecipientLetter();\r\n" +
				"   var stagingDirectory = '" + stagingDirectory + "';\r\n" +
				"   log('showRecipientLetter() - stagingDirectory: ' + stagingDirectory);\r\n" +
				"   log('showRecipientLetter() - recipientId: ' + recipientId);\r\n" +
				"   var d = new Date();\r\n" +
				"   var uniqueId = d.getDate()+d.getMonth() + 1+d.getFullYear()+d.getHours()+d.getMinutes()+d.getSeconds();\r\n" +
				"   var postString = 'directory=' + stagingDirectory" +
				"                     + '&recipientId=' + recipientId + '&uniqueId=' + uniqueId;\r\n" +
				"   log('showRecipientLetter() - postString: ' + postString);\r\n" +
				"   var href = contextRoot + '/ws?command=find.letter&recipientId='" +
			    "     + recipientId+  '&user=' + user + '&uniqueId=' + uniqueId +  '&domainId=' + domainId + '&pcode=' + pcode + " +
			    "        '&time=" + stagingDateMillis + "&senderId=" + sender.getId() + "';\r\n" +
			    "  		remoteCall(href, handleLetterResponse, handleLetterErrorResponse);\r\n" +
		        " };\r\n"
				);

		methods.append(
				" function handleLetterErrorResponse() { \r\n" +
			 	"    alert('An error occurred attempting to contact the remote server.  Data call: ' + href);\r\n" +
				" }\r\n   " +
				"  \r\n   " +
				"  \r\n   " +
				" function handleLetterResponse() { \r\n" +
				"	  // if the readyState code is 4 (Completed) \r\n" +
				"	  // and http status is 200 (OK) we go ahead and get the responseText \r\n" +
				"	  // other readyState codes: \r\n" +
				"	  // 0=Uninitialised 1=Loading 2=Loaded 3=Interactive \r\n" +
				"	  log(\"handleLetterResponse() - Response received from server, processing XML response.\"); \r\n" +
				"	  var xmlhttp = getXmlHttp(); \r\n" +
				"	  if (xmlhttp.readyState == 4) { \r\n" +
				"			if (xmlhttp.status == 200) { \r\n" +
				"					xmlDoc =             \r\n" +
				"						AjxXmlDoc.createFromXml(xmlhttp.responseText); \r\n" +
				"						 \r\n" +
				"					nativeDocument = xmlDoc.getDoc(); \r\n" +
				"					responseXmlNodes = nativeDocument.getElementsByTagName('letter'); \r\n" +
				"					displayLetterResponse(responseXmlNodes); \r\n" +
				"			} else {  \r\n" +
				"				log(\"Not processed - Response status = \" + xmlhttp.status); \r\n" +
				"			} \r\n" +
				"	  } else { \r\n" +
				"			log(\"Not processed - Response readyState = \" + xmlhttp.readyState); \r\n" +
				"	  } \r\n" +
				"	} \r\n" +
				"   \r\n" +
				"   \r\n" 
				);

 			methods.append(
				"	function displayLetterResponse(responseXmlNodes) { \r\n" +
				"		log('displayLetterResponse() - displaying xml response - response count: ' + responseXmlNodes.length);\r\n" +
				"		if (responseXmlNodes.length > 0) {   \r\n" +
				"			node = responseXmlNodes[0]; \r\n" +
				"			var letterBody = node.getAttribute(\"body\"); \r\n" +
				"			var decodedLetterBody = decodeLineFeeds(letterBody); \r\n" +
				"			log('displayLetterResponse() - Letter body: ' + decodedLetterBody);\r\n" +
				"           document.getElementById('letterBody').innerHTML = decodedLetterBody;\r\n" + 
				"           //alert(decodedLetterBody);\r\n" +
				"			var letterHeader = node.getAttribute(\"recipientName\"); \r\n" +
				"           document.getElementById('div_letter_recipient').innerHTML = letterHeader;\r\n" +
				"			var subject = node.getAttribute(\"subject\"); \r\n" +
				"			log('displayLetterResponse() - subject: ' + subject);\r\n" +
				"           document.getElementById('recipSubject').value = subject;\r\n" +
				"           var recipientId = node.getAttribute(\"recipientId\");\r\n" +
				"           document.getElementById('recipientId').value = recipientId;\r\n" +
 				"       }; \r\n" + 
 				"   }; \r\n" 
				);

 			methods.append(
 					"	function saveRecipientLetter() { \r\n" +
 					"       var recipientId = document.getElementById('recipientId').value;\r\n" +
 					"       if (recipientId != 'null') {\r\n " +
 					"           var subject = document.getElementById('recipSubject').value;\r\n" +
 					"           var letterTextArea = document.getElementById('letterBody');\r\n" + 
 				    "           var body = letterTextArea.value;\r\n" +
 					"           log('Saving:\\nRecipient: ' + recipientId + '\\n\\nSubject: ' + subject + '\\n\\nLetter: \\n' + body);\r\n" +
					"           //var form = document.getElementById('form_temp_text');\r\n" + 
					"           //if (form == null) { \r\n" +
					"           //    alert('Error - could not find form for temp text save');\r\n " +
					"           //};\r\n" +
					"           var postString = 'subject=' + encodeURI(subject)" + 
			                         " + '&body=' + encodeURI(body)" +
					                 " + '&senderId=" + sender.getId() +
					                 "&stageTime=" + stagingDateMillis +
					                 "&recipientId=' + recipientId;\r\n" +
					"           log('saveRecipientLetter() - postString' + postString);\r\n" +
					"           post('saveemailjs.do', postString, handleLetterSaveResponse, 899934);\r\n" +
					"           log('saveRecipientLetter() done executing post');\r\n" +
 					"       }\r\n " +
 	 				"   }; \r\n" 
 					);
 			
 			methods.append(
 					"function handleLetterSaveResponse() { \r\n" +
 					"   log('handleLetterSaveResponse() called'); \r\n" +
 				    "}\r\n\r\n");
 			
 			methods.append(
 				"</script>\r\n");

 			
		return(methods.toString());
	}
	
}
